﻿@{
    ViewData["Title"] = "HousingPriceView";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@* 查询条件 *@
<div class="layui-btn-container">
    <div class="layui-form layui-form-pane" style="padding: 20px;">
        <div class="layui-row">
            <div class="layui-col-md6">
                <button type="button" id="btnOpen" class="layui-btn layui-btn-primary layui-border-blue">新增房价计划</button>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <div class="layui-input-block" style="width: 200px;">
                        <select name="roomId" lay-verify="required" lay-filter="changeRoom">
                            <option value="0">请选择房型</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@* 显示 *@
<table class="layui-table" id="demoTable" lay-filter="demoTable">
    <tbody>
    </tbody>
</table>
<div id="demo-laypage-all" style="justify-content: center;display: flex;"> </div>

@* 操作列 *@
<script type="text/html" id="Operation">
    {{# if(d.housingState === 0) { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="ChangeState">启用</a>
    {{# } else { }}
        <a href="#" class="link" style="color:cornflowerblue" lay-event="ChangeState">停用</a>
    {{# } }}
    <a href="#" class="link" style="color:cornflowerblue" lay-event="PriceCalendar">价格日历</a>
    <a href="#" class="link" style="color:cornflowerblue" lay-event="Edit">编辑</a>
    <a href="#" class="link" style="color:cornflowerblue" lay-event="Delete">删除</a>
    <a href="#" class="link" style="color:cornflowerblue" lay-event="PutIn">投放</a>
    <a href="#" class="link" style="color:cornflowerblue" lay-event="Gift">礼</a>
</script>

@* 弹出层 *@
<div id="popupContent" style="display: none;">
    <form class="layui-form" id="myForm">
        <div class="layui-form layui-form-pane" style="padding: 20px;">
            <div class="layui-form-item">
                <label class="layui-form-label">使用房型</label>
                <div class="layui-input-block">
                    <select name="roomId" lay-verify="required">
                        <option value="">请选择房型</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">产品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="productsName" lay-verify="required" placeholder="请输入产品名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">标准价</label>
                <div class="layui-input-block">
                    <input type="text" name="standardPrice" lay-verify="required" placeholder="默认标准价，完成新增后，会员差价可在价格日历设置" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">收款方式</label>
                <div class="layui-input-block">
                    <input type="radio" name="receivablesType" value="1" title="预订付费">
                    <input type="radio" name="receivablesType" value="0" title="到店付费">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">住宿优惠</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="preferential" value="可使用优惠卷抵扣" title="可使用优惠卷抵扣">
                    <input type="checkbox" name="preferential" value="可使用现金卷折扣" title="可使用现金卷折扣">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">会员差价</label>
                <div class="layui-input-block">
                    <input type="radio" name="difference" value="1" title="不设置">
                    <input type="radio" name="difference" value="2" title="按折扣">
                    <input type="radio" name="difference" value="3" title="按不同价格">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">早餐份数</label>
                <div class="layui-input-block">
                    <input type="text" name="breakfast" lay-verify="required" placeholder="请输入早餐份数" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">房量数量</label>
                <div class="layui-input-block">
                    <input type="text" name="roomNum" lay-verify="required" placeholder="请输入房量数量" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">销售策略</label>
                <div class="layui-input-block">
                    <table>
                        <tr>
                            <td>
                                <input type="radio" name="salesStrategy" value="1" title="无" lay-filter="radior">
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="layui-input-block">
                    <table>
                        <tr>
                            <td>
                                <input type="radio" name="salesStrategy" value="2" title="早定优惠,提前" lay-filter="radior">
                            </td>
                            <td style="width:80px">
                                <input type="text" name="reserverDay" value="0" disabled style="height:30px" autocomplete="off" class="layui-input">
                            </td>
                            <td>
                                <label style="margin-left:10px">预订</label>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="layui-input-block">
                    <table>
                        <tr>
                            <td>
                                <input type="radio" name="salesStrategy" value="3" title="限定优惠,最低预订" lay-filter="radior">
                            </td>
                            <td style="width:80px">
                                <input type="text" name="minimumRoomNum" value="0" disabled style="height:30px" autocomplete="off" class="layui-input">
                            </td>
                            <td>
                                <label style="margin-left:10px">间</label>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="submitForm">确认</button>
                    <button type="button" class="layui-btn layui-btn-primary" lay-on="closeFormBtn">取消</button>
                    <button class="layui-btn" lay-submit lay-filter="amend">修改</button>
                    <input type="text" style="display:none" name="housingPricesId"> 
                    <input type="text" style="display:none" name="createdTime"> 
                </div>
            </div>
        </div>
    </form>
</div>
@* <script src="~/rooms/roomhousingprice.js"></script> *@
<script>
    layui.use(['table', 'form', 'layer', 'laypage', 'jquery'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var laypage = layui.laypage;

        // 使用 AJAX 动态加载下拉框选项
        $.get({
            url: 'http://localhost:5174/api/RoomType/GetAllRoom', // 数据接口，这里替换为实际的 AJAX 请求地址
            success: function (data) {
                // 成功获取数据后，动态生成下拉框选项
                var select = $('select[name="roomId"]');
                select.empty(); // 清空下拉框当前的选项
                // 添加默认选项
                select.append('<option value="0">请选择房型</option>');
                // 添加 AJAX 返回的数据作为选项
                $.each(data.data, function (index, item) {
                    select.append('<option value="' + item.roomId + '">' + item.roomName + '</option>');
                });

                // 重新渲染表单
                form.render('select');
            },
            error: function () {
                layer.msg('加载数据失败');
            }
        });

        // 获取房型下拉框的值
        var from = {
            roomId: $("[name=roomId]").val(),
            page: 1,
            size: 15
        }

        //选中单选框启用文本框
        form.on('radio(radior)', function (data) {
            $('input[type="text"][name=reserverDay]').prop('disabled', true);
            $('input[type="text"][name=minimumRoomNum]').prop('disabled', true);

            // 根据选中的单选框启用对应的文本框
            if (data.value === '2') {
                $('[name=reserverDay]').prop('disabled', false);
            } else if (data.value === '3') {
                $('[name=minimumRoomNum]').prop('disabled', false);
            }
            // 执行layui表单的重新渲染，以更新样式
            layui.form.render();
        });

        var total = 0;

        //因为layui就是个就绪函数所以需要放外面
        show()

        // 监听下拉框变化事件
        layui.form.on('select(changeRoom)', function (data) {
            //// 获取下拉框选择的值
            from.roomId = data.value
            show()
        });

        // 监听表格中的操作列事件
        table.on('tool(demoTable)', function (obj) {
            var data = obj.data;
            var event = obj.event;
            console.log(obj.data)
            //更改状态
            if (event === 'ChangeState') {
                // 示例：确认框
                layer.confirm('确定更改启用后，将会开售，请确认价格已设置正确？', function (index) {
                    // // 确认按钮的回调函数，index 为弹出层的索引，一般用不到
                    // layer.close(index); // 关闭弹出层
                    // // 这里可以编写删除操作的代码
                    console.log(obj.data.housingPricesId)
                    $.post({
                        url: 'http://localhost:5174/api/RoomHousingState/ChangeStateHousing',
                        contentType: "application/json",
                        data: JSON.stringify({ housingPricesId: obj.data.housingPricesId }),
                        headers: {
                            "Authorization": "Bearer " + localStorage.getItem('token')
                        },
                        async: true,
                        success: function (res) {
                            console.log(res)
                            if (res.code > 0) {
                                layer.msg('操作成功');
                                // 成功后重新加载数据
                                show()
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    })

                    layer.close(index);
                });
            }
            //价格日历跳转
            else if (event === 'PriceCalendar') {
                location.href = '/HousingPriceState/HousingPricecalCalendarView'
                sessionStorage.setItem("roomId", obj.data.roomId)
                sessionStorage.setItem("productsName", obj.data.productsName)
            }
            //编辑
            else if (event === 'Edit') {
                // 获取外部定义的弹出层内容
                var popupContent = document.getElementById('popupContent').innerHTML;

                // 页面层
                layer.open({
                    type: 1,
                    title: '房价计划',
                    area: ['600px', '750px'], // 宽高
                    content: popupContent,
                    success: function (index, layero) {
                        $("[name=createdTime]").val(obj.data.createdTime)
                        $("[name=housingPricesId]").val(obj.data.housingPricesId)
                        // 将数据填充到表单中
                        $("[name=roomId]").val(obj.data.roomId);
                        $("[name=productsName]").val(obj.data.productsName);
                        $("[name=standardPrice]").val(obj.data.standardPrice);
                        $("input[name=receivablesType][value=" + (obj.data.receivablesType == false ? 0 : 1) + "]").prop('checked', true);
                        $('.layui-input-block input[type="checkbox"]').each(function () {
                            var checkboxValue = $(this).val(); // 获取复选框的值
                            if (obj.data.preferential.includes(checkboxValue)) {
                                $(this).prop('checked', true); // 如果该值在 obj.data.preferential 数组中，则选中复选框
                            } else {
                                $(this).prop('checked', false); // 否则不选中
                            }
                        });
                        $("[name=preferential]").val(obj.data.preferential);
                        $("input[name=difference][value=" + obj.data.difference + "]").prop('checked', true);
                        $("[name=breakfast]").val(obj.data.breakfast);
                        $("[name=reserverDay]").val(obj.data.reserverDay);
                        $("[name=minimumRoomNum]").val(obj.data.minimumRoomNum);
                        $("[name=roomNum]").val(obj.data.roomNum);
                        $("input[name=salesStrategy][value=" + obj.data.salesStrategy + "]").prop('checked', true);
                        form.render();
                    }
                });

                //修改
                form.on('submit(amend)', function (data) {
                    //阻止重复提交
                    data.elem.disabled = true;

                    $.ajax({
                        url: 'http://localhost:5174/api/RoomHousingState/UpdateHousing',
                        type: 'put',
                        contentType: "application/json",
                        data: JSON.stringify(data.field),
                        success: function (res) {
                            // 添加成功后的操作
                            if (res.code > 0) {
                                layer.msg("修改成功");
                                show()
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                    layer.closeAll(); // 关闭所有弹出层
                    return false; // 阻止表单的默认提交
                });

            }
            //删除
            else if (event === 'Delete') {
                // 示例：确认框
                layer.confirm('确定要删除吗？', function (index) {
                    // // 确认按钮的回调函数，index 为弹出层的索引，一般用不到
                    // layer.close(index); // 关闭弹出层
                    // // 这里可以编写删除操作的代码

                    var myArray = [];
                    myArray.push(obj.data.housingPricesId)

                    $.post({
                        url: 'http://localhost:5174/api/RoomHousingState/DeleteHousing',
                        contentType: "application/json",
                        data: JSON.stringify({ housingPricesId: myArray }),
                        headers: {
                            "Authorization": "Bearer " + localStorage.getItem('token')
                        },
                        async: true,
                        success: function (res) {
                            if (res.code > 0) {
                                layer.msg('删除成功');
                                show()
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    })

                    layer.close(index);
                });
            }
            //投放
            else if (event === 'PutIn') {
                layer.msg('待完善投放');
            }
            //礼包
            else if (event === 'Gift') {
                layer.msg('待完善礼');
            }
        });

        //弹出层启动
        $('#btnOpen').on('click', function () {
            // 获取外部定义的弹出层内容
            var popupContent = document.getElementById('popupContent').innerHTML;

            // 页面层
            layer.open({
                type: 1,
                title: '房价计划',
                area: ['600px', '750px'], // 宽高
                content: popupContent,
                success: function (index, layero) {
                    form.render();
                }
            });
        })

        //弹出层添加
        form.on('submit(submitForm)', function (data) {
            console.log(data.field)
            //输入框默认值
            var today = new Date();
            var yyyy = today.getFullYear();
            var mm = String(today.getMonth() + 1).padStart(2, '0'); // January is 0!
            var dd = String(today.getDate()).padStart(2, '0');
            data.field.createdTime = yyyy + '-' + mm + '-' + dd;

            //阻止重复提交
            data.elem.disabled = true;

            $.ajax({
                url: 'http://localhost:5174/api/RoomHousingState/AddHousing',
                type: 'post',
                contentType: "application/json",
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                data: JSON.stringify(data.field),
                success: function (res) {
                    console.log(res.data)
                    // 添加成功后的操作
                    if (res.code > 0) {
                        layer.msg("添加成功");
                        show()
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            });

            layer.closeAll(); // 关闭所有弹出层
            return false; // 阻止表单的默认提交
        });

        // 弹出层取消按钮
        $(document).on('click', '[lay-on="closeFormBtn"]', function () {
            layer.closeAll(); // 关闭所有弹出层
        });

        //定义显示方法
        function show() {
            //获取显示值
            $.post({
                url: 'http://localhost:5174/api/RoomHousingState/GetRoom',
                contentType: "application/json",
                data: JSON.stringify(from),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {
                    total = res.total
                    table.render({
                        elem: '#demoTable',
                        data: res.data,
                        cols: [[
                            { field: 'roomName', title: '房型' },
                            { field: 'productsName', title: '产品名称' },
                            { field: 'breakfast', title: '早餐' },
                            { field: 'preferential', title: '住宿优惠', width: 150 },
                            {
                                field: 'receivablesType', title: '付款方式', templet: function (d) {
                                    return d.receivablesType == true ? "预订付费" : "到店付费"
                                }
                            },
                            {
                                field: 'salesStrategy', title: '价格', templet: function (d) {
                                    return '￥' + d.standardPrice.toFixed(2)
                                }
                            },
                            {
                                field: 'housingState', title: '状态', width: 100, templet: function (d) {
                                    // 根据 receivablesType 的值返回不同的文本
                                    var text = d.housingState == 0 ? "停用" : "启用";
                                    // 设置不同的颜色
                                    var color = d.housingState == 0 ? "red" : "green";
                                    // 返回带有颜色的文本
                                    return '<span style="color: ' + color + ';">' + text + '</span>';
                                }
                            },
                            { field: 'order', title: '排序', width: 100 },
                            { toolbar: '#Operation', width: 300, title: '操作' }
                        ]],
                        page: true,
                        limit: 15,
                        limits: [15, 20, 25]
                    });
                },
                error: function (error) {
                    console.error(error);
                }
            })
        }
    });
</script>